package com.aric.springbootmusic.handler;

import com.aric.springbootmusic.utils.Result;
import com.aric.springbootmusic.utils.ResultUtil;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.security.SignatureException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

//异常处理需要配合异常code来写,异常code需要自己写，枚举类型
@RestControllerAdvice
public class MusicExceptionHandler {
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        Map<String,Object> map=new HashMap<>();
        BindingResult result=e.getBindingResult();
        if(result.hasErrors()){
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (int i = 0,len=fieldErrors.size(); i < len; i++) {
                FieldError field=fieldErrors.get(i);
                map.put(i+"-"+field.getField(),field.getDefaultMessage());
            }
        }
        return ResultUtil.getResponseResult(HttpStatus.METHOD_FAILURE.value(),"方法参数校验不通过异常",map);
    }

    @ExceptionHandler({ExpiredJwtException.class})
    public Result handleExpiredJwtException(ExpiredJwtException e){
        return ResultUtil.getResponseResult(HttpStatus.METHOD_FAILURE.value(),"jwt过期了",null);
    }

    @ExceptionHandler({SignatureException.class})
    public Result handleSignatureException(SignatureException e){
        return ResultUtil.getResponseResult(HttpStatus.METHOD_FAILURE.value(),"签名异常",null);
    }
}
